<template>
  <a-drawer
    width="100%"
    :open="open"
    :get-container="false"
    :style="{ position: 'absolute' }"
    :rootStyle="{ position: 'absolute', height: 'calc(100vh - 48px)' }"
    :bodyStyle="{ background: 'rgb(240, 242, 245)', padding: '16px' }"
    :closable="false"
  >
    <template #title>
      <a-button class="back" type="primary" :icon="h(ArrowLeftOutlined)" @click="goBack">
        返回
      </a-button>
    </template>
    <!-- <div style="padding: 10px; background: #fff; margin-bottom: 10px">
      <a-button class="back" type="primary" :icon="h(ArrowLeftOutlined)" @click="goBack">
        返回
      </a-button>
    </div> -->
    <div class="page">
      <div class="page_left">
        <!-- 患者信息 -->
        <div class="info_card">
          <div class="card_top">
            <img src="@/assets/user.png" alt="" />
            <div class="patient_info">
              <div class="base_info">
                <p>
                  <span class="name">{{ state.patName }}</span>
                  <span>{{ state.age }}岁</span>
                  <span>{{ state.phone }}</span>
                </p>
                <a-rate v-model:value="favorite" :count="1" @change="favoriteChange">
                  <template #character>
                    <StarFilled :style="{ color: favorite ? '#165dff' : '#0000000f' }" />
                  </template>
                </a-rate>
              </div>
              <p>
                管理医生: <span class="doctor_name">{{ state.userName }}</span>
              </p>
              <a-button v-auth="'hp-admin:patientManagement:handleManage'" @click="manualManaBtn">
                <template #icon>
                  <SettingOutlined />
                </template>
                手动管理
              </a-button>
            </div>
          </div>
          <div class="card_bottom">
            <div class="tags">
              <span v-if="state.groupNames">
                <template v-for="tag in state.groupNames.slice(0, 4)" :key="tag">
                  <a-tag v-if="tag" color="blue" style="margin-bottom: 8px; font-size: 14px">
                    {{ tag }}
                  </a-tag>
                </template>
              </span>
              <div v-if="state.groupNames && state.groupNames.length > 4">
                <div v-if="isGroupExpand">
                  <template
                    v-for="tag in state.groupNames.slice(4, state.groupNames.length)"
                    :key="tag"
                  >
                    <a-tag v-if="tag" color="blue" style="margin-bottom: 8px; font-size: 14px">
                      {{ tag }}
                    </a-tag>
                  </template>
                </div>
                <a @click="isGroupExpand = !isGroupExpand">{{ isGroupExpand ? '收起' : '更多' }}</a>
              </div>
            </div>
            <div class="tags">
              <span v-if="state.planNames">
                <template v-for="tag in state.planNames.slice(0, 4)" :key="tag">
                  <a-tag v-if="tag" class="success" style="margin-bottom: 8px; font-size: 14px">
                    {{ tag }}
                  </a-tag>
                </template>
              </span>
              <div v-if="state.planNames && state.planNames.length > 4">
                <div v-if="isPlanExpand">
                  <template
                    v-for="tag in state.planNames.slice(4, state.planNames.length)"
                    :key="tag"
                  >
                    <a-tag v-if="tag" class="success" style="margin-bottom: 8px; font-size: 14px">
                      {{ tag }}
                    </a-tag>
                  </template>
                </div>
                <a @click="isPlanExpand = !isPlanExpand">{{ isPlanExpand ? '收起' : '更多' }}</a>
              </div>
            </div>
          </div>
        </div>
        <!-- 诊疗事件时间轴 -->
        <div class="time_axis">
          <div class="title">
            <p>
              <span class="line"></span>
              <span>关键诊疗事件时间轴</span>
            </p>
          </div>
          <div class="time_axis_body">
            <a-timeline mode="left">
              <a-timeline-item v-for="(item, index) of timeAxis" :key="index" :label="item.time">
                <template #dot>
                  <div class="dot">
                    <div class="active"></div>
                  </div>
                </template>
                <div class="time_treat">{{ item.treatTypeName }}</div>
                <div class="time_title">{{ item.title }}</div>
                <div class="time_content">{{ item.content }}</div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </div>
      </div>
      <div class="page_right">
        <a-tabs v-model:activeKey="activeKey" type="card" @change="tabsKeyChange">
          <a-tab-pane key="1" tab="健康信息">
            <HealthInfo ref="healthInfoRef"></HealthInfo>
          </a-tab-pane>
          <a-tab-pane key="2" tab="就诊记录">
            <VisitRecords ref="visitRecordsRef"></VisitRecords>
          </a-tab-pane>
          <a-tab-pane key="3" tab="管理活动记录">
            <ManaActivity ref="manaActivityRef"></ManaActivity>
          </a-tab-pane>
          <a-tab-pane key="4" tab="操作记录">
            <OperateRecords ref="operaterecordsRef"></OperateRecords>
          </a-tab-pane>
          <a-tab-pane key="5" tab="随访表单">
            <a-spin :spinning="state.followUpSpinning" tip="加载中...">
              <followUp :childProp="state.followUpObj" @resetDetail="resetDetail"></followUp>
            </a-spin>
          </a-tab-pane>
          <a-tab-pane key="6" tab="不良反应">
            <a-spin :spinning="state.adverseSpinning" tip="加载中...">
              <adverseReactions
                :childProp="state.adverseReactionsObj"
                @sendState="sendState"
                @ignoreState="ignoreState"
              >
              </adverseReactions>
            </a-spin>
          </a-tab-pane>
          <a-tab-pane key="7" tab="未复查患者">
            <a-spin :spinning="state.unreviewedSpinning" tip="加载中...">
              <unreviewedPatient
                :childProp="state.unreviewedReactionsObj"
                @sendUnreviewedState="sendUnreviewedState"
                @ignoreUnreviewedState="ignoreUnreviewedState"
              ></unreviewedPatient>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <ManualMana ref="manualManaRef" @close="manualManaData"></ManualMana>
  </a-drawer>
</template>

<script lang="ts" setup name="数据管理">
import { ref, reactive, onMounted, h, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { StarOutlined, SettingOutlined, ArrowLeftOutlined, StarFilled } from '@ant-design/icons-vue'
import {
  addFavorite,
  cancelFavorite,
  getTreatLine,
  getInfoDetail,
  adverseDetail,
  sendMsg,
  adverseUpdates,
  remindDetail,
  remindFinished,
  remindUpdates,
  followDetail,
  templateListAll,
  followTopOne,
  adverseTopOne,
  remindTopOne,
  getUserList
} from '@/api/patientManagement/index.ts'
import HealthInfo from './health-info/index.vue'
import followUp from './followUp/index.vue'
import adverseReactions from './adverseReactions/index.vue'
import unreviewedPatient from './unreviewedPatient/index.vue'
import { useRoute } from 'vue-router'
import ManualMana from './manual-mana.vue'
import VisitRecords from './visit-records/index.vue'
import ManaActivity from './mana-activity/index.vue'
import OperateRecords from './operate-records/index.vue'
const props = defineProps(['childProp'])
const route = useRoute()

const open = ref(false)

const timeAxis = ref([])
const activeKey = ref('1')
const favorite = ref()

const state = reactive({
  patName: '',
  age: '',
  phone: '',
  favorite: false,
  userName: '',
  followUpSpinning: false,
  adverseSpinning: false,
  adverseReactionsObj: {},
  unreviewedSpinning: false,
  unreviewedReactionsObj: {},
  patientId: '',
  groupId: '',
  followUpObj: {},
  doctorList: [],
  templateList: [],
  listIds: '',
  stateAdverse: false
})
const isGroupExpand = ref(false)
const isPlanExpand = ref(false)
const emit = defineEmits(['close'])

const healthInfoRef = ref()

const visitRecordsRef = ref()
const manaActivityRef = ref()
const operaterecordsRef = ref()
const patIds: any = ref()
watch(
  props,
  (newValue) => {
    if (newValue.childProp && newValue.childProp.length > 0) {
      state.doctorList = []
      state.doctorList = newValue.childProp
    }
  },
  { immediate: true, deep: true }
)
const init = async (listId, id, patId) => {
  activeKey.value = '1'
  open.value = true
  if (route.query && route.query.tabId) {
    activeKey.value = route.query.tabId
    state.patientId = route.query.id
    state.patientIdTwo = route.query.patId
    if (route.query.tabId == 5) {
      state.followUpSpinning = true
      state.templateList = []
      await templateListAll({ templateType: '3' }).then((res) => {
        state.templateList = res.data
      })
      let doctorListParam = {}
      await getUserList().then((res) => {
        doctorListParam = res.data
      })
      await followDetail({ id: route.query.id })
        .then((res) => {
          state.followUpSpinning = false
          state.followUpObj.obj = res.data
          state.followUpObj.id = route.query.id
          state.followUpObj.doctorList = doctorListParam
          //   state.followUpObj.doctorList = state.doctorList
          state.followUpObj.templateList = state.templateList
        })
        .catch(() => {
          state.followUpSpinning = false
        })
    } else if (route.query.tabId == 6) {
      state.adverseSpinning = true
      adverseDetail({ id: route.query.id })
        .then((res) => {
          state.adverseSpinning = false
          state.adverseReactionsObj = res.data
        })
        .catch(() => {
          state.adverseSpinning = false
        })
    } else if (route.query.tabId == 7) {
      state.unreviewedSpinning = true

      remindDetail({ id: Number(state.patientId) })
        .then((res) => {
          state.unreviewedSpinning = false
          state.unreviewedReactionsObj = res.data
        })
        .catch(() => {
          state.unreviewedSpinning = false
        })
    }
  } else {
    state.groupId = id
    state.patientId = patId
    state.patientIdTwo = patId
    state.listIds = listId
  }

  isPlanExpand.value = false
  isGroupExpand.value = false
  timeAxis.value = []
  patIds.value = patId
  getInfo(id, patId, listId)

  getTreatLine({ patId: patId }).then((res) => {
    res.data.forEach((element) => {
      timeAxis.value.push({
        treatTypeName: element.treatTypeName,
        title: element.itemName,
        content: element.itemValue,
        time: element.executeTime,
        active: false
      })
    })
  })
}

const getInfo = async (id, patId, listId) => {
  await getInfoDetail({ patId: patId, groupId: id }).then((res) => {
    Object.assign(state, res.data)
    state.listIds = res.data.id
    if (state.favorite) {
      favorite.value = 1
    } else {
      favorite.value = 0
    }
    healthInfoRef.value.init(patId, state.groupName, res.data.id)
  })
}

const resetDetail = () => {
  tabsKeyChange('5', 'topOne')
}
// 手动管理
const manualManaRef = ref()
const manualManaBtn = () => {
  manualManaRef.value.init(
    patIds.value,
    state.groupName,
    state.groupId,
    state.patName,
    state.deptCode
  )
}
const manualManaData = () => {}
const tabsKeyChange = (value, result) => {
  switch (value) {
    case '1':
      healthInfoRef.value.init(patIds.value, state.groupName, state.listIds)
      break
    case '2':
      nextTick(() => {
        visitRecordsRef.value.init(patIds.value)
      })
      break
    case '3':
      nextTick(() => {
        manaActivityRef.value.init(patIds.value)
      })
      break
    case '4':
      nextTick(() => {
        operaterecordsRef.value.init(patIds.value)
      })
      break
    case '5':
      nextTick(async () => {
        state.followUpSpinning = true
        state.templateList = []
        await templateListAll({ templateType: '3' }).then((res) => {
          state.templateList = res.data
        })
        let doctorListParam = {}
        await getUserList().then((res) => {
          doctorListParam = res.data
        })
        if (result == 'topOne') {
          await followTopOne({ patId: state.patientIdTwo, groupId: state.groupId })
            .then((res) => {
              state.followUpSpinning = false
              state.followUpObj.id = res.data && res.data.id ? res.data.id : route.query.id
              state.followUpObj.doctorList = doctorListParam
              // state.followUpObj.doctorList = state.doctorList
              state.followUpObj.obj = res.data
              state.followUpObj.templateList = state.templateList
            })
            .catch(() => {
              state.followUpSpinning = false
            })
        } else {
          if (route.query && route.query.tabId) {
            await followDetail({ id: route.query.id })
              .then((res) => {
                state.followUpSpinning = false
                state.followUpObj.obj = res.data
                state.followUpObj.id = res.data && res.data.id ? res.data.id : route.query.id
                state.followUpObj.doctorList = doctorListParam
                //   state.followUpObj.doctorList = state.doctorList
                state.followUpObj.templateList = state.templateList
              })
              .catch(() => {
                state.followUpSpinning = false
              })
          } else {
            await followTopOne({ patId: state.patientIdTwo, groupId: state.groupId })
              .then((res) => {
                state.followUpSpinning = false
                state.followUpObj.id = res.data && res.data.id ? res.data.id : route.query.id
                state.followUpObj.doctorList = doctorListParam
                // state.followUpObj.doctorList = state.doctorList
                state.followUpObj.obj = res.data
                state.followUpObj.templateList = state.templateList
              })
              .catch(() => {
                state.followUpSpinning = false
              })
          }
        }
      })
      break
    case '6':
      nextTick(() => {
        state.adverseSpinning = true
        adverseTopOne({ patId: state.patientIdTwo, groupId: state.groupId })
          .then((res) => {
            state.adverseSpinning = false
            state.adverseReactionsObj = res.data
          })
          .catch(() => {
            state.adverseSpinning = false
          })
      })
      break
    case '7':
      nextTick(() => {
        state.unreviewedSpinning = true
        remindTopOne({ patId: state.patientIdTwo, groupId: state.groupId })
          .then((res) => {
            state.unreviewedSpinning = false
            state.unreviewedReactionsObj = res.data
          })
          .catch(() => {
            state.unreviewedSpinning = false
          })
      })
  }
}

const goBack = () => {
  if (route.query && route.query.patId) {
    window.history.go(-1)
  } else {
    open.value = false
    activeKey.value = '1'
    emit('close')
  }
}
// 发送提醒
const sendState = (item) => {
  let param = {
    id: '',
    remindContext: ''
  }
  if (route.query && route.query.tabId) {
    if (state.stateAdverse == false) {
      param = item
      state.stateAdverse = true
    } else {
      param.id = state.adverseReactionsObj.id
      param.remindContext = item.remindContext
    }
  } else {
    param.id = state.adverseReactionsObj.id
    param.remindContext = item.remindContext
  }
  state.adverseSpinning = true
  sendMsg(param)
    .then((res) => {
      state.adverseSpinning = false
      message.success('发送提醒成功')
      tabsKeyChange('6')
    })
    .catch(() => {
      state.adverseSpinning = false
    })
}

// 忽略
const ignoreState = (item) => {
  let param = {
    id: '',
    remindContext: ''
  }
  if (route.query && route.query.tabId) {
    // param = item
    console.log(1111)
    if (state.stateAdverse == false) {
      param = item
      state.stateAdverse = true
    } else {
      console.log(3333)

      param.id = state.adverseReactionsObj.id
      param.remindContext = item.remindContext
    }
  } else {
    param.id = state.adverseReactionsObj.id
    param.remindContext = item.remindContext
  }
  state.adverseSpinning = true
  adverseUpdates(param)
    .then((res) => {
      state.adverseSpinning = false
      message.success('忽略成功')
      tabsKeyChange('6')
    })
    .catch(() => {
      state.adverseSpinning = false
    })
}

// 未复查患者 完成
const sendUnreviewedState = (item) => {
  let param = {
    id: '',
    remindResult: ''
  }
  if (route.query && route.query.tabId) {
    param = item
  } else {
    param.id = state.unreviewedReactionsObj.id
    param.remindResult = item.remindResult
  }
  state.unreviewedSpinning = true
  remindFinished(param)
    .then((res) => {
      state.unreviewedSpinning = false
      message.success('任务处理完成')
      tabsKeyChange('7')
    })
    .catch(() => {
      state.unreviewedSpinning = false
    })
}
const ignoreUnreviewedState = (item) => {
  let param = {
    id: '',
    remindResult: ''
  }
  if (route.query && route.query.tabId) {
    param = item
  } else {
    param.id = state.unreviewedReactionsObj.id
    param.remindResult = item.remindResult
  }
  state.unreviewedSpinning = true
  remindUpdates(param)
    .then((res) => {
      state.unreviewedSpinning = false
      message.success('忽略成功')
      tabsKeyChange('7')
    })
    .catch(() => {
      state.unreviewedSpinning = false
    })
}

const favoriteChange = async (value) => {
  state.favorite = value ? true : false
  if (value) {
    await addFavorite({ id: state.id, patId: state.patId }).then((res) => {
      message.success('收藏成功')
    })
  } else {
    await cancelFavorite({ id: state.id, patId: state.patId }).then((res) => {
      message.success('取消收藏成功')
    })
  }
  isPlanExpand.value = false
  isGroupExpand.value = false
  getInfo(state.groupId, state.patId, state.listIds)
}
defineExpose({
  init
})
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  display: flex;

  .page_left {
    width: 30%;
    margin-right: 16px;
  }

  .page_right {
    width: 75%;
    background: #fff;
    padding: 16px 24px;
    border-radius: 8px;
  }

  .info_card {
    padding: 24px;
    border-radius: 8px;
    background: #fff;
    width: 100%;
    box-sizing: border-box;

    .card_top {
      display: flex;
      padding-bottom: 16px;
      position: relative;

      img {
        width: 64px;
        height: 64px;
        border-radius: 50%;
        margin-right: 16px;
      }

      .patient_info {
        width: 100%;

        .base_info {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        p {
          margin-bottom: 8px;
          font-size: 14px;
          color: #4e5969;
          font-weight: 400;

          span {
            margin-right: 16px;
          }

          .name {
            font-size: 20px;
            font-weight: 500;
            color: #1d2129;
          }

          .doctor_name {
            color: #1d2129;
          }
        }
      }
    }

    .card_bottom {
      border-top: 1px dashed #e5e6eb;
      padding-top: 16px;

      .tags {
        &:first-child {
          margin-bottom: 6px;
        }
      }
    }
  }

  .time_axis {
    padding: 24px;
    border-radius: 8px;
    background: #fff;
    width: 100%;
    margin-top: 16px;
    box-sizing: border-box;

    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24px;

      .line {
        display: inline-block;
        margin-right: 8px;
        width: 3px;
        height: 16px;
        background: #165dff;
      }

      p {
        span {
          font-size: 18px;
          font-weight: 600;
          color: #1d2129;
        }
      }
    }

    .time_axis_body {
      padding-right: 40px;
      min-height: 340px;

      .dot {
        width: 24px;
        overflow: hidden;
        background: #fff;

        div {
          width: 12px;
          height: 12px;
          margin: 6px auto;
          background: #e5e6eb;
          border-radius: 50%;

          &.active {
            background: #165dff;
          }
        }
      }

      .time_content {
        white-space: pre-wrap;
      }
    }
  }
}

.time_treat {
  font-weight: 600;
  color: #1d2129;
}

.time_title,
.time_content {
  color: #86909c;
  font-size: 12px;
}

.success {
  color: #00b42a;
  background: #e8ffea;
  border-color: #00b42a;
}
</style>
